<template>
  <div>
    <van-nav-bar title="地址管理" left-arrow @click-left="$router.back()">
      <template #right>
        <van-icon name="ellipsis" />
      </template>
    </van-nav-bar>

    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="onSelect"
    />
  </div>
</template>

<script>
import { APIgetAddressList } from "@/http/index.js";
import Vue from "vue";
import { AddressList } from "vant";

Vue.use(AddressList);

export default {
  name: "AddressList",
  props: [],
  data() {
    return {
      chosenAddressId: 0,
      list: [],
    };
  },
  created() {
    APIgetAddressList().then((res) => {
      if (res.resultCode == 200) {
        this.list = res.data.map((item) => {
          let one = {
            id: item.addressId,
            name: item.userName,
            tel: item.userPhone,
            address: item.provinceName + item.regionName + item.detailAddress,
            isDefault: Boolean(item.defaultFlag),
          };
          return one;
        });
        this.getChosenId();
      }
    });
  },
  mounted() {},
  methods: {
    onAdd() {
      this.$router.push("/addressAdd");
    },
    onEdit(val) {
      this.$router.push("/addressEdit/" + val.id);
    },
    getChosenId() {
      if (this.list.length > 0) {
        this.chosenAddressId =
          this.list.find((item) => item.isDefault == 1)?.id || 0;
      }
    },
    onSelect(val) {
      //console.log(val)
      this.$router.push("/create-order/" + val.id);
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less"></style>
